package com.cloud.example.config.timer;

import com.cloud.async.business.context.data.TimerDataSource;
import com.cloud.async.business.context.data.abs.AbsDataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.ObjectUtils;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * 自定义数据源配置
 * @author chengrui
 */
public class RealizableTimerConfig implements AbsDataSource {

    /**
     * logger
     */
    private final Log logger = LogFactory.getLog(getClass());

    private TimerDataSource<String, CompletableFuture<String>> timerDataSource = new TimerDataSource<>();

    @Override
    public int getCount() {
        return timerDataSource.size();
    }

    @Override
    public String[] getKeyNames() {
        return new String[0];
    }

    @Override
    public boolean includeKey(String key) {
        return timerDataSource.containsKey(key);
    }

    @Override
    public void releaseData(String key) {
        timerDataSource.releaseData(key);
    }

    @Override
    public String getResult(String key, Long milliSecond) {
        String ret = null;
        try {
            if (includeKey(key)) {
                CompletableFuture<String> function = timerDataSource.getDateByKey(key);
                ret = ObjectUtils.isEmpty(function) ? "{}" : function.get(milliSecond, TimeUnit.MILLISECONDS);
            }
        } catch (Exception e) {
            logger.error("TimerExpireData getResult Error :" + e.getMessage());
        } finally {
            releaseData(key);
        }
        return ret;
    }

    @Override
    public Boolean saveData(String key, CompletableFuture value) {
        try {
            timerDataSource.put(key, value);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}

